<?php

declare(strict_types=1);

namespace App\Amqp\Consumer;

use Hyperf\Amqp\Annotation\Consumer;
use Hyperf\Amqp\Message\ConsumerMessage;
use PhpAmqpLib\Message\AMQPMessage;
use Hyperf\Amqp\Message\Type;
use Hyperf\Amqp\Result;
use Service\Consumer\YunCangConsumer\YunCangCommodityMessageConsumerService;
use Service\Code\Normal;
use Service\MonitorService\MonitorService;

/**
 * 云仓商品消费中心
 * @Consumer(exchange="YC_PUSH_BBC_RECEIVE_LIST", routingKey="YC_PUSH_BBC_RECEIVE_LIST", queue="YC_PUSH_BBC_RECEIVE_LIST", nums=1)
 */
class YunCangCommodityMessageConsumer extends ConsumerMessage
{
    protected $type = Type::DIRECT;//直连模式
    protected $qos  = [
        'prefetch_count'    => 10
    ];
    public function consumeMessage($data, AMQPMessage $message): string
    {
        try {
            
            $result = YunCangCommodityMessageConsumerService::instance()->consumer(
                (int)$data['sid'],
                (int)$data['cid'],
                (string)$data['MessageType'],
                (array)$data['data'],
                (string)($data['logid'] ?? '0'),
                (int)($data['IsFinished'] ?? 0),
                );
            if( $result['code'] == Normal::SUC ) {
                return Result::ACK;
            }
            
            $contents = json_encode($result,JSON_UNESCAPED_UNICODE);
            MonitorService::instance()->sendMsg($contents,'YC_PUSH_BBC_RECEIVE_LIST队列消费异常');
            
            //处理失败的情况
            sleep(3);//休眠3秒之后，重回队列
            return Result::REQUEUE;
        } 
        catch ( \Throwable $t ) 
        {
            $error = [
                'error'         => $t->getMessage(),
                'errorFile'     => $t->getFile(),
                'errorLine'     => $t->getLine(),
            ];
            
            $contents = json_encode($error,JSON_UNESCAPED_UNICODE);
            MonitorService::instance()->sendMsg($contents,'YC_PUSH_BBC_RECEIVE_LIST队列消费异常');
            sleep(3);//休眠3秒之后，重回队列
            return Result::REQUEUE;
        }
    }
    
    /**
     * 设置是否自启动
     */
    public function isEnable() : bool
    {
        $isDisAable = env('AMQP_BBC_RECEIVE_COMMODITY_MESSAGE_CONSUMER_DISABLE');
        return $isDisAable ? false : true ;
    }
}